package org.gp953.org.service.impl;

import org.gp953.basic.exception.BusinessException;
import org.gp953.basic.service.impl.BaseServiceImpl;
import org.gp953.org.domain.Employee;
import org.gp953.org.domain.Shop;
import org.gp953.org.mapper.EmployeeMapper;
import org.gp953.org.mapper.ShopMapper;
import org.gp953.org.service.IEmployeeService;
import org.gp953.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    @Transactional
    public void register(Shop shop) {
        Employee admin = shop.getAdmin();
        //  校验2次密码是否一致
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("2次密码输入不一致，请重新输入");
        }

        // 校验账号，电话，邮箱
        Employee employeeUserName =  employeeMapper.queryByUserName(admin.getUsername());
        System.out.println(employeeUserName);
        Employee employeeEmail =  employeeMapper.queryByEmail(admin.getEmail());
        System.out.println(employeeEmail);
        Employee employeePhone =  employeeMapper.queryByPhone(admin.getPhone());
        if(employeeUserName != null){
            throw new BusinessException("账号已经注册了，请重新输入，如果是想要添加新的店铺，您可以直接登陆后在店铺管理页面添加");
        } else {
            if(employeePhone != null){
                throw new BusinessException("手机号已经注册了，请重新输入，如果是想要添加新的店铺，您可以直接登陆后在店铺管理页面添加");
            } else {
                if(employeeEmail != null){
                    throw new BusinessException("邮箱已经注册了，请重新输入，如果是想要添加新的店铺，您可以直接登陆后在店铺管理页面添加");
                }
            }
        }

        // 入驻逻辑：店铺的管理员id不能为空所以要把admin作为员工保存，
        // 再保存店铺信息，最后再更新员工信息对应的店铺id
        // 先保存店铺管理员并返回自增长id
        employeeMapper.save(admin);
        // 把员店铺管理员的自增长id存到店铺对象中，并保存店铺到数据库，并返回自增长id
        shop.setAdmin(admin);
        shopMapper.save(shop);
        // 再把店铺的自增长id更新到该管理员的店铺id中
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("ruhuajiaosiyutou@163.com");
        mailMessage.setSubject("您的店铺加盟申请已通过！");
        mailMessage.setText("您的账号："+admin.getUsername()+"<br/>密码:"+admin.getPassword());
        mailMessage.setTo("ruhuajiaosiyutou@163.com");
        javaMailSender.send(mailMessage);
    }
}
